package cn.iocoder.yudao.adminserver.modules.tool.controller.test;

import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 图片上传
 *
 * @author <a href="jiangfeng.yan@ikang.com">jiangfeng</a>
 * @version 2021年05月10日 下午 3:26
 */
@Slf4j
@RestController
@Api(value = "上传下载单个文件", tags = {"上传下载单个文件"})
@RequestMapping("/file")
public class UpdateController {

    @ApiOperation("上传图片")
    @PostMapping("/uploadImage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "multipartFile", value = "图片文件", required = true, dataTypeClass = MultipartFile.class)
    })
    @ResponseBody
    public CommonResult uploadImage(@RequestParam("multipartFile") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            throw new ServiceException(-1, "请选择图片");
        }

//        //检查格式
//        String fileType = multipartFile.getContentType();
//        log.info("文件类型：" + fileType);
//        boolean flag = false;
//        List<String> uploadImageTypes = Arrays.asList("png", "jpg", "jpeg", "gif");
//        for (String type : uploadImageTypes) {
//            if (fileType.equals(type)) {
//                flag = true;
//                break;
//            }
//        }
//        if (!flag) {
//            throw new ServiceException(-1, "请选择 png、jpg、jpeg、gif、bmp 格式的图片");
//        }

        //检查文件大小
        double imageSize = (double) multipartFile.getSize() / 1024 / 1024;
        if (imageSize > 10 * 1024 * 1024) {
            throw new ServiceException(-1, "请上传10M以内图片");
        }
        //文件名
        String fileName = multipartFile.getOriginalFilename();
        //后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
        String format = simpleDateFormat.format(new Date());

        //文件存储位置
        String path = "/home/ruoyi/uploadPath/" + format;
        //图片名
        fileName = IdUtil.fastSimpleUUID() + suffixName;
        //图片的url
        String imageUrl = path + "/" + fileName;
        log.info("图片URL：" + imageUrl);
        File dest = new File(imageUrl);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
            return success(imageUrl);
        } catch (IOException e) {
        }
        return error(-1, "上传失败！");
    }

    @ApiOperation("获取图片")
    @GetMapping("/getImage")
    @ResponseBody
    public void getImage(@RequestParam String imageUrl, HttpServletResponse response) {
        if (imageUrl != null) {
            log.info("请求的图片URL：" + imageUrl);
            FileInputStream in = null;
            OutputStream out = null;
            try {
                File file = new File(imageUrl);
                if (!file.exists()) {
                    throw new ServiceException(-1, "图片不存在");
                }
                in = new FileInputStream(imageUrl);
                int i = in.available();
                byte[] buffer = new byte[i];
                in.read(buffer);
                //设置输出流内容格式为图片格式
                response.setContentType("image/jpeg");
                //response的响应的编码方式为utf-8
                response.setCharacterEncoding("utf-8");
                out = response.getOutputStream();
                out.write(buffer);
            } catch (Exception e) {
                throw new ServiceException(-1, "网络错误");
            } finally {
                try {
                    in.close();
                    out.close();
                } catch (IOException e) {
                    throw new ServiceException(-1, "网络错误");
                }
            }
        }
    }


    public static void main(String[] args) {
        System.out.println("System.getProperty(\"user.dir\") = " + System.getProperty("user.dir"));

    }
}
